package main

import (
	"fmt"
	"git.oschina.net/cnjack/nightc-queue/queue"
	"github.com/Unknwon/goconfig"
	"net/http"
	"os"
	"strconv"
)

type Option struct {
	Port string
}

var option Option
var Qlist map[string]*queue.Queue

func init() {
	ReadConfig()
}

//配置的读取
func ReadConfig() {
	Qlist = make(map[string]*queue.Queue)
	conf, err := goconfig.LoadConfigFile("./conf.ini")
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(0)
	}
	option.Port, err = conf.GetValue("queue", "port")
	if err != nil {
		option.Port = "8080"
	}
}

func pushHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Credentials", "true")
	pushdata := r.FormValue("q")
	database := r.FormValue("d")
	if database == "" {
		w.Write([]byte("database is not select"))
		return
	}
	if pushdata == "" {
		w.Write([]byte("push data is empty"))
		return
	}
	Qlist[database].Push(pushdata)
	w.Write([]byte("ok"))
}
func pullHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Credentials", "true")
	database := r.FormValue("d")
	if database == "" {
		w.Write([]byte("database is not select"))
		return
	}
	fmt.Fprintf(w, Qlist[database].Pull())
}
func countHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Credentials", "true")
	database := r.FormValue("d")
	if database == "" {
		w.Write([]byte("database is not select"))
		return
	}
	w.Write([]byte(strconv.Itoa(Qlist[database].Count())))
}
func createHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Credentials", "true")
	size, _ := strconv.Atoi(r.FormValue("s"))
	databasename := r.FormValue("d")
	if databasename == "" {
		w.Write([]byte("databasename is not define"))
		return
	}
	if r.FormValue("s") == "" {
		w.Write([]byte("size is not define"))
		return
	}
	size = 1024
	Qlist[databasename] = queue.NewQueue(size)
	fmt.Fprintf(w, "ok")
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Credentials", "true")
	fmt.Fprintf(w, "welcome to use go-queue")
}
func main() {
	fmt.Println(option.Port + " is Listening")
	http.HandleFunc("/push", pushHandler)
	http.HandleFunc("/pull", pullHandler)
	http.HandleFunc("/create", createHandler)
	http.HandleFunc("/count", countHandler)
	http.HandleFunc("/", indexHandler)
	http.ListenAndServe(":"+option.Port, nil)
}
